package com.shqcjd.preinstallmobile.ui.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.ExpertListBean;
import com.shqcjd.preinstallmobile.ui.adapter.ExpertListAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.SpacesItemDecoration;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 专家列表
 */
public class ExpertListActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.et_search_expert)
    EditText etSearchExpert;
    @BindView(R.id.rv_expert_list)
    RecyclerView rvExpertList;
    private ExpertListAdapter expertListAdapter;
    private int expertType;


    //分页
    private int mNextRequestPage = 1;
    private static final int PAGE_SIZE = 6;
    private String name;
    private View notDataView;
    private int equipmentId;
    private int taskId;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_expert_list;
    }

    @Override
    public void initView() {
        expertType = getIntent().getIntExtra("expertType", 0);
        equipmentId = getIntent().getIntExtra("equipmentId", -1);
        taskId = getIntent().getIntExtra("TaskId", -1);
        tvToolbarCenter.setText("专家列表");
        initExperList();

    }

    @Override
    public void initData() {
        name = "";
        refreshData();
    }

    private void initExperList() {
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvExpertList.getParent(), false);
        expertListAdapter = new ExpertListAdapter();
        rvExpertList.setLayoutManager(new LinearLayoutManager(this));
        rvExpertList.addItemDecoration(new SpacesItemDecoration(UIUtils.dip2px(10), UIUtils.dip2px(9)));
        rvExpertList.setAdapter(expertListAdapter);
        expertListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ExpertListBean.ItemsBean item = (ExpertListBean.ItemsBean) adapter.getItem(position);
                Intent intent = new Intent(ExpertListActivity.this, ExpertDetailActivity.class);
                intent.putExtra("ExpertId", item.id);
                intent.putExtra("equipmentId", equipmentId);
                intent.putExtra("taskId", taskId);
                startActivity(intent);
            }
        });
        expertListAdapter.setOnLoadMoreListener(this,rvExpertList);
        expertListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ExpertListBean.ItemsBean item = (ExpertListBean.ItemsBean) adapter.getItem(position);
                Intent intent = new Intent(ExpertListActivity.this, WaitingAnswerActivity.class);
                intent.putExtra("remoteId", item.id);
                intent.putExtra("equipmentId", equipmentId);
                intent.putExtra("taskId", taskId);
                intent.putExtra("icon", item.icon);
                startActivity(intent);
            }
        });


        etSearchExpert.addTextChangedListener(new TextWatcher() {



            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name = s.toString();
                refreshData();
            }
        });


    }

    private void refreshData() {
        mNextRequestPage = 1;
        expertListAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", ""+mNextRequestPage);
        map.put("pageSize", ""+PAGE_SIZE);
        map.put("expert_type", ""+expertType);//专家类型 1专家 2专工 3供应商 0全部
        map.put("expert_name", name);

        ApiService.getExpertList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ExpertListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<ExpertListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            setData(true, retData.data.items);
//                            expertListAdapter.setNewData(retData.data.items);
                        } else {
                            ToastUtils.showShort(ExpertListActivity.this, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        expertListAdapter.setEnableLoadMore(true);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        expertListAdapter.setEnableLoadMore(true);
                    }
                });
    }

    private void setData(boolean isRefresh, List data) {

        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                expertListAdapter.setNewData(data);
            } else {
                expertListAdapter.setNewData(null);
                expertListAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                expertListAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            expertListAdapter.loadMoreEnd(isRefresh);
        } else {
            expertListAdapter.loadMoreComplete();
        }
    }




    @OnClick(R.id.iv_toolbar_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void loadMore() {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", ""+mNextRequestPage);
        map.put("pageSize", ""+PAGE_SIZE);
        map.put("expert_type", ""+expertType);//专家类型 1专家 2专工 3供应商 0全部
        map.put("expert_name", name);

        ApiService.getExpertList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ExpertListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<ExpertListBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.items);
                        } else {
                            ToastUtils.showShort(ExpertListActivity.this, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        expertListAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }
}
